package com.love.poetry.infrastructure.persist.security.impl;

import org.springframework.stereotype.Repository;

import com.love.poetry.domain.security.User;
import com.love.poetry.infrastructure.persist.security.UserRepository;
import com.youboy.core.orm.mybatis.MybatisRepositorySupport;

@Repository
public class MybatisUserRepository extends
		MybatisRepositorySupport<String, User> implements UserRepository {

	@Override
	protected String getNamespace() {
		return "com.love.poetry.domain.security.User";
	}

	public User lazyGet(String id) {
		return (User) getSqlSession().selectOne(
				getNamespace().concat(".lazyGet"), id);
	}

	public User queryUniqueByUsername(String username) {
		return (User) getSqlSession().selectOne(
				getNamespace().concat(".queryUniqueByUsername"), username);
	}

	public void markLocked(String[] ids) {
		getSqlSession().update(getNamespace().concat(".markLocked"), ids);
	}

	public void markNotLocked(String[] ids) {
		getSqlSession().update(getNamespace().concat(".markNotLocked"), ids);
	}

	@Override
	public void save(User entity) {
		super.save(entity);
		if (entity.hasRole()) {
			getSqlSession().insert(getNamespace().concat(".saveRoles"), entity);
		}
	}

	@Override
	public void update(User entity) {
		super.update(entity);
		getSqlSession().delete(getNamespace().concat(".deleteRoles"), entity);
		if (entity.hasRole()) {
			getSqlSession().insert(getNamespace().concat(".saveRoles"), entity);
		}
	}

	public boolean checkUserAuthority(String username) {
		return null == getSqlSession().selectOne(
				getNamespace().concat(".checkUserAuthority"), username);
	}

    public boolean existsByUsername(String username) {
                return null != getSqlSession().selectOne(getNamespace().concat(".existsByUsername" ), username);
   }

}
